package hehe.container.util;

import java.lang.reflect.Field;
import java.lang.reflect.ParameterizedType;
import java.util.*;

/**
 * 日志帮助类
 *<B>说明：</B>
 *<pre>
 * 略
 *</pre>
 *<B>示例：</B>
 *<pre>
 *  略
 *</pre>
 *<B>日志：</B>
 *<pre>
 *  略
 *</pre>
 *<B>注意事项：</B>
 *<pre>
 *  略
 *</pre>
 */
public class ReflectUtil
{
    /**
     * 首字母大小
     *<B>说明：</B>
     *<pre>
     * 属性详细描述
     *</pre>
     */
    public static String upperCase(String str)
    {
        char[] ch = str.toCharArray();
        if (ch[0] >= 'a' && ch[0] <= 'z') {
            ch[0] = (char) (ch[0] - 32);
        }

        return new String(ch);
    }


    /** 以下为　设置对象属性相关方法*/

    /**
     * 字段定义缓存列表
     *<B>说明：</B>
     *<pre>
     * 通过反射获取Field对象后缓存于此
     *</pre>
     */
    private static final Map<Class<?>,Map<String,Field>> declaredFieldsCache =
            new HashMap<>();

    /**
     * 获取对象属性
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     * @param target 目标对象
     */
    public static Map<String,Object> getAttrs(Object target)
    {
        Class targetClazz = target.getClass();
        Map<String,Field> fields = getFields(targetClazz);
        if (fields.size() == 0) {
            return null;
        }

        Map<String,Object> attrs = new HashMap<>();
        Field field;
        for (Map.Entry<String, Field> fieldSet : fields.entrySet()) {
            try {
                field = fieldSet.getValue();
                field.setAccessible(true);
                attrs.put(fieldSet.getKey(),field.get(target));
            } catch (Exception e) {
                // 不做任何事情
            }
        }

        return attrs;
    }

    /**
     * 设置对象属性值
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     * @param target 属性名
     * @param attrs 对象属性列表
     */
    public static void setAttrs(Object target,Map<String,Object> attrs)
    {
        Class targetClazz = target.getClass();
        String fieldName;
        Field field;
        Map<String,Field> fields = getFields(targetClazz);
        if (fields.size() == 0) {
            return;
        }

        for (Map.Entry<String, Object> attr : attrs.entrySet()) {
            try {
                fieldName = attr.getKey();
                if (fields.containsKey(fieldName)) {
                    field = fields.get(fieldName);
                    field.setAccessible(true);
                    field.set(target,attr.getValue());
                }
            } catch (Exception e) {
                // 不做任何事情
            }
        }
    }

    public static List<String> getFieldsName(Class<?> clazz)
    {
        Map<String,Field> fields = getFields(clazz);
        Set<String> keys = fields.keySet();
        List<String> names = new ArrayList<>();
        for (String key:keys) {
            names.add(key);
        }
        return names;
    }

    /**
     * 获取类全部字段
     *<B>说明：</B>
     *<pre>
     * 方法详细描述
     *</pre>
     */
    public static Map<String,Field> getFields(Class<?> clazz)
    {

        if (!declaredFieldsCache.containsKey(clazz)) {
            // 重新读取
            Map<String,Field> fields = getDeclaredFields(clazz);
            declaredFieldsCache.put(clazz,fields.size() > 0 ? fields : new HashMap());
        }

        return declaredFieldsCache.get(clazz);
    }

    /**
     * 获取类全部字段
     *<B>说明：</B>
     *<pre>
     * 略
     *</pre>
     * @return 未找道属性则，返回null
     */
    public static Map<String,Field> getDeclaredFields(Class<?> clazz)
    {
        Map<String,Field> clazzFields = new HashMap<>();
        List<Class> superClazzs = findSuperclass(clazz);
        Collections.reverse(superClazzs);

        for (Class<?> superClazz : superClazzs) {
            Field[] fields = superClazz.getDeclaredFields() ;
            for (Field field : fields) {
                clazzFields.put(field.getName(),field);
            }
        }

        return clazzFields;
    }

    /**
     * 查找对应父类
     *<B>说明：</B>
     *<pre>
     * 略
     *</pre>
     */
    public static List<Class> findSuperclass(Class<?> clazz)
    {

        Class<?> targetClazz = clazz;
        List<Class> superClazzs = new ArrayList<>();
        superClazzs.add(clazz);

        while (true) {//当父类为null的时候说明到达了最上层的父类(Object类).
            targetClazz = targetClazz.getSuperclass(); //得到父类,然后赋给自己
            if (targetClazz != null && targetClazz != Object.class) {
                superClazzs.add(targetClazz);
            } else {
                break;
            }
        }

        return superClazzs;
    }

    /**
     * 获取字段类型
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    public static String getFieldType(Field field)
    {
        String fieldType = field.getGenericType().getTypeName();
        if (fieldType.startsWith("class ")) {
            fieldType = fieldType.substring(6);
        }

        return fieldType;
    }

    /**
     * 获取字段类型
     *<B>说明：</B>
     *<pre>
     *  略
     *</pre>
     */
    public static String getFieldType(Field field,int pos)
    {
        ParameterizedType pt = (ParameterizedType)field.getGenericType();
        String fieldType =  pt.getActualTypeArguments()[pos].getTypeName();
        if (fieldType.startsWith("class ")) {
            fieldType = fieldType.substring(6);
        }

        return fieldType;
    }
}
